<?php

class DefaultController extends Controller_index
{
	public function actionIndex()
	{
                $model=new Party();
                $cmodel=new Children();
                $model->setScenario('register'); 
                if(isset($_POST['Party']))
                {
                     if($_POST['Party']['next']==50){
                         
                        //用于验证是否是分享的用户浏览
                        Yii::app()->session['message']='true';
                         
                        $model->attributes=$_POST['Party'];
                        $model->validate();
                         
                        $username=$model->getError('username');
                        $phone=$model->getError('phone');
                        $vcode=$model->getError('vcode');
                        $company=$model->getError('company');

                        $province=$model->getError('province');
                        $city=$model->getError('city');
                        $area=$model->getError('area');
                        $address=$model->getError('address');
                        $code=$model->getError('code');
                        
                     
                       
                        

                            $res_v=TRUE;
                            
                  
                            if(!empty($username)){
                                 $res_v=FALSE;
                             }

                             if(!empty($phone)){
                                 $res_v=FALSE;
                             }

                             if(!empty($vcode)){
                                 $res_v=FALSE;
                             }

                             if(!empty($company)){
                                 $res_v=FALSE;
                             }

                             if(!empty($province)){
                                 $res_v=FALSE;
                             }

                             if(!empty($city)){
                                 $res_v=FALSE;
                             }

                             if(!empty($area)){
                                 $res_v=FALSE;
                             }
                             if(!empty($address)){
                                 $res_v=FALSE;
                             }
                             if(!empty($code)){
                                 $res_v=FALSE;
                             }
                             

                             
                            if($res_v){
                              //第一个页面
                                echo 1;
                             }  else {
                                echo CActiveForm::validate($model);//有错误信息返回给页面
                             }
    
                            Yii::app()->end();
                            die(); 
                     }else{

                        //第二个页面
                        $transaction = Yii::app()->db->beginTransaction(); //创建事务
                        $model->attributes=$_POST['Party'];
                        $model->is_origin=1;
                        $model->is_float=0;
                        $model->is_use=1;
                        $model->is_send=0;
                        $model->is_from=1;
                        $model->add_time=date('y-m-d H:i:s',time());
                        
                         //获取车辆座位
                        $f_num=0;
                        $p_num=0;
                        if(!empty($model->ad_id)){
                            $connection = Yii::app()->db;  
                            $sql = "SELECT (count(*)+ (SELECT COUNT(*) FROM party WHERE ad_id=".$model->ad_id.")) as 'val' FROM children  WHERE party_id in (SELECT id FROM party WHERE ad_id=".$model->ad_id.") ";  
                            $command = $connection->createCommand($sql);  
                            $result = $command->queryAll();  
                            $f_num=$result[0]['val'];      
                            $p=  ActivityDetail::model()->findByPk($model->ad_id);
                            $p_num=$p->astrict;
                        }
                        
                        //用户识别码
                        $temp_code;
                        $snumber=new Snumber();
                        $snumber->add_time=date('y-m-d H:i:s',time());
                        if($snumber->save()){
                           $temp_code=$snumber->attributes['id'];
                        }else{
                             $transaction->rollback(); //回滚事务
                             Yii::app()->end();
                             die();           
                        }
//                        $model->user_code=date('Ymd',time()).str_pad($temp_code,6,"0",STR_PAD_LEFT).$this->generate_code(2);
                        $model->user_code="2".substr(date('Y',time()),2).str_pad($temp_code,6,"0",STR_PAD_LEFT);
                        //人群属性()
                        $model->crowd_id=ActivityDetail::model()->findByPk($model->ad_id)->crowd_id;
                        if($model->save()){

//                            //带孩子参
                            if($_POST['Party']['is_children']!=2){
                                
                                if(empty($model->children_num)){
                                   echo '{"Party_children_num":["儿童数量 不可为空白."]}';//有错误信息返回给页面
                                                    $transaction->rollback(); //回滚事务
                                                    Yii::app()->end();
                                                    die();                                                    
                                }  
                                
                                
                                if(isset($_POST['Children'])){
                                     $cmodel->attributes=$_POST['Children'];    
                                            if(!empty($model->ad_id)){
                                                $c_num=count($cmodel->username);
                                                $sum_num=$f_num+$c_num;
                                                if($sum_num>=$p_num){
                                                    echo '{"Party_ad_id":["您选择的车辆名额已满，请选择其他车辆"]}';//有错误信息返回给页面
                                                    $transaction->rollback(); //回滚事务
                                                    Yii::app()->end();
                                                    die();                                                    
                                                }   
                                            }   
                                    
                                    for($i=0;$i<count($cmodel->username);$i++){
                                             if(!empty($cmodel->username[$i])){
                                                     $c=new Children();
                                                     $c->username=$cmodel->username[$i];
                                                     $c->sex=$cmodel->sex[$i];
                                                     $c->age=$cmodel->age[$i];
                                                     $c->grade=$cmodel->grade[$i];
                                                     $c->school=$cmodel->school[$i];
                                                     $c->party_id=$model->id;
                                                     if($c->save()){    

                                                     }else{
                                                        echo CActiveForm::validate($c);//有错误信息返回给页面
                                                         $transaction->rollback(); //回滚事务
                                                         Yii::app()->end();
                                                         die();
                                                     }
                                             }else{
                                                    echo '{"Children_username":["儿童姓名不可为空"]}';//有错误信息返回给页面
                                                 $transaction->rollback(); //回滚事务
                                                 Yii::app()->end();
                                                 die();
                                             }
                                    }//循环结束
                                    
                                    $num=$model->children_num;
                                    $count=count($cmodel->username);
                                    if($num!=$count){
                                        echo '{"Children_username":["需要填写'.$num.'个儿童的信息"]}';//有错误信息返回给页面
                                        $transaction->rollback(); //回滚事务
                                        Yii::app()->end();
                                        die();                                                
                                    }   
                                    
                                    $black=Blacklist::model()->count("phone='".$model->phone."' and code='".$model->code."'");
                                    if($black>0)
                                        echo 3;
                                    else
                                        echo 2;
                                    //$this->smsMessage($model->phone,"您已预约‘欣和爱生活食育体验馆’的参观体验，如当天预约人数不满15人，则会电话再次协调您的时间，请随时保持手机的畅通。");                                   
                                } // end $_POST['Children']
                              
                            }else{
                                 //不带孩子参加
                                 if($f_num>=$p_num){
                                    echo '{"Party_ad_id":["您选择的车辆名额已满，请选择其他车辆"]}';//有错误信息返回给页面
                                    $transaction->rollback(); //回滚事务
                                    Yii::app()->end();
                                    die();                                                    
                                }
                                $black=Blacklist::model()->count("phone='".$model->phone."' and code='".$model->code."'");
                                if($black>0)
                                  echo 3;
                                else
                                  echo 2;
                               //$this->smsMessage($model->phone,"您已预约‘欣和爱生活食育体验馆’的参观体验，如当天预约人数不满15人，则会电话再次协调您的时间，请随时保持手机的畅通。");
                            }
                            
                            
                        //新增地址逻辑
                        //先改用户表的内容
                        $p_count=Party::model()->updateAll(array('is_use'=>'0'),"phone='".$model->phone."' and code='".$model->code."' and id !=".$model->primaryKey);
                        if($p_count>0){
                            //再修改新增表的地址
                            $n_count=Naddress::model()->updateAll(array('is_used'=>'0'),"phone='".$model->phone."' and code='".$model->code."'");
                        } 
                            
    
                        }else{
                             echo CActiveForm::validate($model);//有错误信息返回给页面
                        }
                        
                        
                        
                        
                        $transaction->commit(); //提交事务
                        Yii::app()->end();
                        die();
                     }
                     //end 第二个页面
                     

                }
                //end提交数据

                $this->render('index',array(
                       'model'=>$model,
                       'cmodel'=>$cmodel,
               ));
	}
        
        public function actionMessage()
	{
           
                $model=new Party;
                
                if(empty(Yii::app()->session['message'])){
                     $this->redirect(array('default/index'));
                }
                
		 $this->render('message',array(
                       'model'=>$model,
               ));
	}
        
        
        public function actionMes()
	{
           
                $model=new Party;
                
                if(empty(Yii::app()->session['message'])){
                     $this->redirect(array('default/index'));
                }
                
		 $this->render('black',array(
                       'model'=>$model,
               ));
	}
        
        
        public function actionLine($id){
             echo CJSON::encode(LineDetail::model()->with('position')->findAll("ad_id=".$id));
        }

        public function actionResult($val)
	{
               $str= base64_decode($val);
                $id=substr($str,8);
                $model=new Party;
                $model=Party::model()->findByPk($id);
                
                if(empty($model)){
                    $this->redirect(array('default/error'));
                }

		 $this->render('result',array(
                       'model'=>$model,
               ));
	}
        
        
        //发送短信
        function smsMessage($s_phone,$s_txt){
                require_once("nusoap.php");
                $soapclient = new nusoap_client("http://www.shinho.com.cn/sendsms/Service1.asmx?wsdl",true);
                $soapclient->soap_defencoding = 'UTF-8';
                $soapclient->decode_utf8 = false;
                $parameters = array("phone"=>$s_phone, "s_txt"=>$s_txt);
                $result = $soapclient->call('SendSMS',$parameters);
                return $result;
        }
        
        
         //验证码
        public function actionSms($id)
	{
                $model=new Party();
                $sms= new Captcha();
                $s_count=$sms::model()->find('phone='.$id);
                
                 if(count($s_count)>0){
                  // $ddate= strtotime($s_count->create_time) - strtotime(time());
                    $minute=floor((strtotime($s_count->create_time)-strtotime(date('Y-m-d H:i:s',time())))%86400/60);
                    echo $minute;
                    if($minute<-30){
                        $code=$this->generate_code(4);
                    }else{
                        $code=$s_count->code;
                    }
                    
                 }else{
                    $code= $this->generate_code(4);
                 }
                if($_POST["code_times"]<=0){
                    require_once("nusoap.php");
                    $soapclient = new nusoap_client("http://www.shinho.com.cn/sendsms/Service1.asmx?wsdl",true);
                    $soapclient->soap_defencoding = 'UTF-8';
                    $soapclient->decode_utf8 = false;
         //         $s_phone = "15192385771";
                    $s_phone = $id;

                    $s_txt = "您的验证码为：".$code.'。感谢您报名参与欣和企业“社会大课堂”的活动。';
                    $parameters = array("phone"=>$s_phone, "s_txt"=>$s_txt);
                    $result = $soapclient->call('SendSMS',$parameters);                    
                }else{
                    //载入ucpass类
                    require_once('html/Ucpaas.class.php');
                    //初始化必填
                    $options['accountsid']='c96a4e12a7410f81a0a9ab9f0a89629d';
                    $options['token']='d02cec04a6b580c1e7cbb21972585111';
                    //初始化 $options必填
                    $ucpass = new Ucpaas($options);
                    //开发者账号信息查询默认为json或xml
                    echo $ucpass->getDevinfo('xml');                                       
                    $s_phone = $id;
                    $appId = "5909864e2cf94589a072905a14c07758";
                    $verifyCode = $code;
                    $to = $s_phone;
                    $ucpass->voiceCode($appId,$verifyCode,$to);                      
                }
                if(count($s_count)>0){
                   $s_count->code=$code;
                   $s_count->phone=$id;
                   $s_count->create_time=date('Y-m-d H:i:s',time());
                   $s_count->save();
                }else{
                   $sms->code=$code;
                   $sms->phone=$id;
                   $sms->create_time=date('Y-m-d H:i:s',time());
                   $sms->save();
                }
                
                echo CJSON::encode(1);

            $this->render('sms',array(
                    'model'=>$model,
            ));
	}      
       /**
	 * Performs the AJAX validation.
	 * @param WxJoin $model the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='wx-join-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
        function generate_code($length = 4) {
            return rand(pow(10,($length-1)), pow(10,$length)-1);
        }
        /**
         * 团体报名验证
         */
        public function actionTuanti($id){
//            $code=$_POST['Party'];
            $result=0;
            $detial=ActivityDetail::model()->find("invitation_code='".$id."'");
            if(count($detial)>0){
                $time= date('Y-m-d H:i:s',time());
                //报名人数
                $connection = Yii::app()->db;
                $sql="SELECT (count(*)+ (SELECT COUNT(*) FROM party WHERE is_from!=3 AND ad_id=".$detial->id.")) as 'count' FROM children  WHERE party_id in (SELECT id FROM party WHERE is_from!=3 AND ad_id=".$detial->id.")";
                $command_1 = $connection->createCommand($sql);  
                $result_1 = $command_1->queryAll();  
                $num_1=$result_1[0]['count'];  
                //闭馆
                if ($detial->is_float==0 || $time>$detial->end){
                    $result=-1;
                //报名已满
                }elseif($detial->is_float == 3 || $detial->astrict<=$num_1 ){
                  $result=-2;
                }  else {
                  $result=$detial->id;
                  //用于验证是否是分享的用户浏览
                  unset(Yii::app()->session['invitation_code']);
                  Yii::app()->session['invitation_code']=$result;
                }
            }
            //
//            $a_count=ActivityDetail::model()->find("invitation_code='".$id."' and is_float=1");
//            
//            if (count($a_count)>0){
//                $result=$a_count->id;
//                //用于验证是否是分享的用户浏览
//                unset(Yii::app()->session['invitation_code']);
//                Yii::app()->session['invitation_code']=$result;
//            }
            echo $result;
        }
        /**
         * 点击量
         */
        public function actionClick(){
            $date=date('Y-m-d',time());
            $result= ClickRate::model()->find("date='".$date."'");
            if(count($result)>0){
                $click_no=$result->click_no;
                $click_no++;
                ClickRate::model()->updateByPk($result->id, array('click_no'=>$click_no));
                echo $result->id;
            }  else {
                $model= new ClickRate;
                $model->unsetAttributes();
                $model->click_no=1;
                $model->date=$date;
                $r=$model->save();
                echo $r;
//                ClickRate::model()->insert(array('click_no'=>1,'date'=>$date));
            }
            
        }

        /**
         * 个人报名
         */
        public function actionGeren(){
            unset(Yii::app()->session['invitation_code']);
            Yii::app()->session['invitation_code']=0;
            echo 0;
        }
        
        public function actionPartyTime(){
            
            $invitation_code=0;
            if (!empty(Yii::app()->session['invitation_code'])){
                $invitation_code=Yii::app()->session['invitation_code'];
            }
            if ($invitation_code>0){
                $pmodel=  ActivityDetail::model()->findAll("id=".$invitation_code);    
            }else{
                $time= date('Y-m-d H:i:s',time());
                $pmodel=  ActivityDetail::model()->findAll("is_float=1 and start<='".$time."' and end>='".$time."'");                                     
            }
            
             echo CJSON::encode($pmodel);
        }
}